<template>
  <div class="authContainer">
    <div class="searchRow">
      <div class="inputRow">
        <div class="inputBox">
          <div class="labelText">{{ $t('common.roleName') }}：</div>
          <a-input v-model:value="queryForm.pageModel.query.role_name0" :placeholder="globalI18n.t('common.roleName')"
            :allowClear="true"></a-input>
        </div>
      </div>
      <div class="btnBox">
        <a-button type="primary" @click="getTableData()" class="queryBtn">
          {{ $t('common.query') }}
        </a-button>
        <a-button class="resetBtn" @click="reset">{{ $t('common.reset') }}</a-button>
      </div>
    </div>

    <div class="tableOperation">
      <div class="operationBtn">
        <a-button type="primary" @click="showModel(2)" class="queryBtn">
          {{ $t('common.add') }}
        </a-button>
      </div>
      <a-table :columns="tableData.columns" :pagination="pagination" :data-source="tableData.data">
        <template #headerCell="{ column }">
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'sex'">
            <span v-if="record.sex === 0">{{ $t('sex.male') }}</span>
            <span v-else-if="record.sex === 1">{{ $t('sex.female') }}</span>
          </template>
          <template v-else-if="column.key === 'status'">
            <span>
              <a-tag v-if="record.status === 0" color="#87d068">{{ $t('status.enable') }}</a-tag>
              <a-tag v-if="record.status === 1" color="#c9c5c5">{{ $t('status.disable') }}</a-tag>
            </span>
          </template>
          <template v-else-if="column.key === 'action'">
            <span>
              <a class="actionBtn" @click="handleDeleteRole(record.id)">{{ $t('common.delete') }}</a>
              <a-divider type="vertical" />
              <a class="actionBtn" @click="showModel(1, record)">{{ $t('common.edit') }}</a>
            </span>
          </template>
        </template>
      </a-table>
    </div>

    <a-modal v-model:open="model1" :title="modelTitle" @ok="handleAddEditRole">
      <template #footer>
        <a-button class="cancelBtn" key="back" @click="model1 = false">{{ $t('common.cancel') }}</a-button>
        <a-button class="confirmBtn" key="submit" type="primary" :loading="loading1" @click="handleAddEditRole">{{
          $t('common.confirm') }}</a-button>
      </template>

      <a-form ref="formRef" :model="editRecord" :rules="rules" :label-col="labelCol">
        <a-form-item :label="$t('common.roleName')" name="roleName">
          <a-input v-model:value="editRecord.roleName" />
        </a-form-item>
        <a-form-item :label="$t('common.roleKey')" name="roleKey">
          <a-input v-model:value="editRecord.roleKey" />
        </a-form-item>
        <a-form-item :label="$t('common.sort')" name="sort">
          <a-input-number id="inputNumber" v-model:value="editRecord.roleSort" :min="1" />
        </a-form-item>
        <a-form-item :label="$t('common.status')" name="status">
          <a-switch v-model:checked="editRecord.statusOrigin" :checked-children="$t('status.enable')"
            :un-checked-children="$t('status.disable')" />
        </a-form-item>
        <a-form-item :label="$t('common.remark')" name="remark">
          <a-textarea v-model:value="editRecord.remark" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { deleteRole, findRolePage, updateRole } from '@/api/role';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { Modal, message } from 'ant-design-vue';
import { computed, h, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

// 国际化
const globalI18n = useI18n();
// 编辑/新增角色弹框
const loading1 = ref(false);
// 编辑/新增角色参数
const editRecord = reactive({
  id: null,
  roleName: null,
  roleKey: null,
  roleSort: 0,
  status: null,
  statusOrigin: false,
});
// 弹框标题
const modelTitle = ref('');
// 弹框显示/隐藏
const model1 = ref(false);
// 标签宽度
const labelCol = {
  style: {
    width: '90px',
  },
};
const tableData = reactive({
  columns: computed(() => [
    {
      title: globalI18n.t('common.no'),
      dataIndex: 'no',
      key: 'no',
      resizable: true,
      width: 50,
      customRender: ({ index }) => (pagination.current - 1) * pagination.pageSize + index + 1,
    },
    {
      title: globalI18n.t('common.roleName'),
      dataIndex: 'role_name',
      key: 'role_name',
      resizable: true,
      maxWidth: 150,
    },
    {
      title: globalI18n.t('common.roleKey'),
      dataIndex: 'role_key',
      key: 'role_key',
    },
    {
      title: globalI18n.t('common.sort'),
      key: 'role_sort',
      dataIndex: 'role_sort',
      maxWidth: 80,
    },
    {
      title: globalI18n.t('common.status'),
      key: 'status',
      dataIndex: 'status',
      maxWidth: 90,
    },
    {
      title: globalI18n.t('common.remark'),
      key: 'remark',
      dataIndex: 'remark',
      maxWidth: 90,
    },
    {
      title: globalI18n.t('common.createTime'),
      dataIndex: 'create_time',
      key: 'create_time',
      resizable: true,
      maxWidth: 150,
    },
    {
      title: globalI18n.t('common.action'),
      key: 'action',
    },
  ]),
  data: [],
});

// 监听 vue-i18n 的 locale 变化
watch(() => globalI18n.locale.value, (newVal) => {
  console.log('Language changed to:', newVal);
  getTableData();
});

// 查询对象
const queryForm = reactive({
  pageModel: {
    pageNow: 1,
    pageSize: 10,
    query: {
      role_name0: '',
    }
  }
});

// 定义响应式的分页对象
const pagination = reactive({
  class: 'myPagination',
  total: 0, // 总条数
  current: 1, // 当前页数
  pageSize: 10, // 每页显示的条数
  // pageSizeOptions: ['10', '20', '30', '40', '50'],
  showSizeChanger: true, // 是否可以改变每页显示的条数
  showQuickJumper: true, // 是否可以快速跳转到指定页
  showTotal: (total) => `共 ${total} 条`, // 显示总条数和当前数据范围
  onShowSizeChange: (current, pageSize) => handleShowSizeChange(current, pageSize), // 改变每页数量时更新显示
  onChange: (page, pageSize) => handleShowPageChange(page, pageSize) // 页码改变时的回调函数
});

// 处理每页显示条数改变的函数
const handleShowSizeChange = (current, pageSize) => {
  console.log(current, pageSize);
  pagination.pageSize = pageSize;
};

// 处理页码改变的函数
const handleShowPageChange = (page, pageSize) => {
  console.log('handleShowPageChange.', page, pageSize);
  pagination.current = page;
};

onMounted(() => {
  getTableData();
});
// 重置查询条件
const reset = () => {
  queryForm.pageModel.query.role_name0 = '';
  getTableData();
}

const getTableData = () => {
  queryForm.pageModel.pageSize = pagination.pageSize;
  queryForm.pageModel.pageNow = pagination.current;
  findRolePage(queryForm).then((res) => {
    if (res.code === 200) {
      console.log(res.data);
      tableData.data = res.data.list.dataList;
    }
  }).catch((err) => {
  });
}
// 删除用户
const handleDeleteRole = (id) => {
  Modal.confirm({
    title: globalI18n.t('tips.deleteConfirm'),
    icon: h(ExclamationCircleOutlined),
    content: '',
    okText: `${globalI18n.t('common.confirm')}`,
    okType: 'danger',
    cancelText: `${globalI18n.t('common.cancel')}`,
    onOk() {
      deleteRole(id).then((res) => {
        if (res.code === 200) {
          getTableData();
          message.success(globalI18n.t('tips.deleteSuccess'));
        }
      });
    },
    onCancel() { },
  });
}
// 显示弹框
const showModel = (val, record) => {
  model1.value = true;
  if (val === 1) {
    modelTitle.value = globalI18n.t('role.editRole');
    editRecord.id = record.id;
    editRecord.roleName = record.role_name;
    editRecord.roleKey = record.role_key;
    editRecord.roleSort = record.role_sort;
    editRecord.statusOrigin = record.status == 0 ? true : false;
    editRecord.remark = record.remark;
  } else if (val === 2) {
    modelTitle.value = globalI18n.t('role.addRole');
    editRecord.id = null;
    editRecord.roleName = null;
    editRecord.roleKey = null;
    editRecord.roleSort = null;
    editRecord.statusOrigin = false;
    editRecord.remark = null;
  }
}
// 添加/编辑角色
const handleAddEditRole = () => {
  editRecord.status = editRecord.statusOrigin ? 0 : 1;
  updateRole(editRecord).then((res) => {
    if (res.code === 200) {
      message.success(globalI18n.t('tips.editSuccess'));
      model1.value = false;
      getTableData();
    }
  }).catch((err) => { });
}
</script>

<style scoped lang="scss">
.authContainer {

  .searchRow {
    display: flex;
    background-color: #fff;
    padding: 20px;
    justify-content: space-between;
    margin-top: 20px;
    margin-bottom: 20px;
    flex-wrap: wrap;

    .inputRow {
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .inputBox {
        display: flex;
        align-items: center;
        margin-right: 70px;
        margin-top: 10px;
        margin-bottom: 10px;

        .labelText {
          white-space: nowrap;
          font-size: 14px;
        }

        .selectClass {
          width: 199px;
        }
      }
    }

    .btnBox {
      display: flex;
      flex-wrap: nowrap;

      button {
        margin: 10px 0 10px 9px;
      }

      .ant-btn:first-child {
        margin-right: 8px !important;
      }
    }
  }

  .tableOperation {
    .custom-table {
      padding: 10px;
    }

    background-color: #fff;

    .operationBtn {
      display: flex;
      justify-content: right;
      margin-bottom: 20px;
    }

    padding: 20px;
  }

  .actionBtn {
    color: #4ab44a;

    &:hover {
      color: #388b38;
    }
  }

}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-input-number-focused {
  border-color: #4ab44a;
}

:where(.css-dev-only-do-not-override-1p3hq3p).ant-input-number {

  &:hover,
  &:focus {
    border-color: #4ab44a;
  }
}

.ant-input-number-input:hover {
  background-color: #fff;
  border: 1px solid #4ab44a;
}
</style>
